package api

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"go-admin-server/app/dao/model"
	"go-admin-server/app/dto/response"
	"go-admin-server/app/service"
	"net/http"
)

type userApi struct{}

func NewUserHttp(group *gin.RouterGroup) {
	s := &userApi{}
	group.POST("/user", s.Create)
	group.PUT("/user", s.Update)
	group.DELETE("/user", s.Delete)
}

func (u *userApi) List(c *gin.Context) {

}

func (u *userApi) Create(c *gin.Context) {
	var userDto model.User
	if err := c.BindJSON(userDto); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	if err := service.UserService.Validate(&userDto); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	err := service.UserService.Create(&userDto)
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}
	response.Success(c, userDto)
}

func (u *userApi) Update(c *gin.Context) {
	user := new(model.User)
	if err := c.BindJSON(user); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	logrus.Infof("update user: %#v", user)
	err := service.UserService.Update(user)
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}
	response.Success(c, user)
}

func (u *userApi) Delete(c *gin.Context) {
	var ids []int
	if err := c.BindJSON(ids); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	err := service.UserService.Delete(&ids)
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
	}
	response.Success(c, nil)
}
